package com.ruoyi.web.controller.report;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.IReportDataService;
import com.ruoyi.system.service.IReportFieldConfigService;
import com.ruoyi.system.domain.ReportFieldConfig;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 采购汇总报表Controller
 * 
 * @author ruoyi
 * @date 2025-10-23
 */
@RestController
@RequestMapping("/report/purchSummary")
public class PurchSummaryReportController extends BaseController
{
    @Autowired
    private IReportDataService reportDataService;

    @Autowired
    private IReportFieldConfigService reportFieldConfigService;

    /**
     * 查询采购汇总报表列表
     */
    @PreAuthorize("@ss.hasPermi('report:purchSummary:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody Map<String, Object> params)
    {
        // 修改type参数为2(采购)
        params.put("type", 2);
        startPage();
        List<Map<String, Object>> list = reportDataService.selectReportData("purch_summary", params);
        return getDataTable(list);
    }

    /**
     * 导出采购汇总报表
     */
    @PreAuthorize("@ss.hasPermi('report:purchSummary:export')")
    @Log(title = "采购汇总报表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody Map<String, Object> params)
    {
        try
        {
            // 修改type参数为2(采购)
            params.put("type", 2);
            // 获取报表数据
            List<Map<String, Object>> list = reportDataService.selectReportData("purch_summary", params);
            
            // 获取字段配置
            List<ReportFieldConfig> fieldConfigs = reportFieldConfigService.selectListFieldsByReportCode("purch_summary");
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("采购汇总报表");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            for (int i = 0; i < fieldConfigs.size(); i++)
            {
                ReportFieldConfig config = fieldConfigs.get(i);
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(config.getFieldLabel());
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            for (int i = 0; i < list.size(); i++)
            {
                Row dataRow = sheet.createRow(i + 1);
                Map<String, Object> data = list.get(i);
                
                for (int j = 0; j < fieldConfigs.size(); j++)
                {
                    ReportFieldConfig config = fieldConfigs.get(j);
                    Cell cell = dataRow.createCell(j);
                    Object value = data.get(config.getFieldName());
                    if (value != null)
                    {
                        cell.setCellValue(value.toString());
                    }
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < fieldConfigs.size(); i++)
            {
                sheet.autoSizeColumn(i);
            }
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "采购汇总报表_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 输出
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        }
        catch (IOException e)
        {
            logger.error("导出采购汇总报表异常", e);
        }
    }
}
